package com.haitaoit.chengquan.module.home.activity.pinpai;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.ScrollView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.haitaoit.chengquan.R;
import com.haitaoit.chengquan.base.BackCall;
import com.haitaoit.chengquan.base.BaseActivity;
import com.haitaoit.chengquan.module.home.adapter.BrandAdapter;
import com.haitaoit.chengquan.module.home.model.BrandModel;
import com.haitaoit.chengquan.utils.Constant;
import com.haitaoit.chengquan.utils.DateTimeUtil;
import com.haitaoit.chengquan.utils.GetSign;
import com.haitaoit.chengquan.utils.HttpUtilsSingle;
import com.haitaoit.chengquan.utils.NameValuePairSign;
import com.haitaoit.chengquan.utils.ToastUtils;
import com.haitaoit.chengquan.view.MyListView;
import com.haitaoit.chengquan.view.PullToRefreshBase;
import com.haitaoit.chengquan.view.PullToRefreshScrollView;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.view.annotation.ViewInject;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class BrandActivity extends BaseActivity implements PullToRefreshBase.OnRefreshListener<ScrollView> {
    @ViewInject(R.id.pullrefreshscrollview)
    PullToRefreshScrollView pullrefreshscrollview;

    private ScrollView mScrollView;
    private LinearLayout null_information_layout;
    private MyListView listView;


    private boolean mIsLoad = false;
    private int page = 1;
    private int firstLoade = 0;
    private BrandAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView_V(R.layout.activity_brand);
        setTitle_V("机床品牌推荐");
        setLeftShow(1, R.mipmap.left);
        backLeft_V();
        ViewUtils.inject(this);


        View view = LayoutInflater.from(this).inflate(R.layout.scrollview_listview_layout, null);
        null_information_layout = (LinearLayout) view.findViewById(R.id.null_information_layout);
        listView = (MyListView) view.findViewById(R.id.scrollview_listview);

        pullrefreshscrollview.setPullLoadEnabled(false);
        pullrefreshscrollview.setPullRefreshEnabled(false);
        pullrefreshscrollview.setOnRefreshListener(this);
        pullrefreshscrollview.setLastUpdatedLabel(DateTimeUtil
                .getFormatDateTime(DateTimeUtil.getCurrTimestamp()));
        mScrollView = pullrefreshscrollview.getRefreshableView();
        mScrollView.setFillViewport(true);
        mScrollView.setVerticalScrollBarEnabled(false);
        mScrollView.addView(view);

        adapter = new BrandAdapter(this);
        adapter.setBackCall(backCall);
        listView.setAdapter(adapter);
        httpGetBrandList();
    }

    BackCall backCall = new BackCall() {
        @Override
        public void deal(int which, Object... obj) {
            int position = (Integer) obj[0];
            Intent intent = new Intent();
            switch (which) {
                case R.id.brand_itemll:
                    intent.setClass(BrandActivity.this, BrandDetailActivity.class);
                    String name = adapter.getList().get(position).getName();
                    intent.putExtra("id", adapter.getList().get(position).getId());
                    intent.putExtra("titlename", name);
                    startActivity(intent);
                    break;
            }
            super.deal(which, obj);
        }
    };

    private void httpGetBrandList() {
        int i = (int) Math.floor(Math.random() * 9000 + 1000);
        List<NameValuePairSign> list = new ArrayList<NameValuePairSign>();
        list.add(new NameValuePairSign("rnd", i + ""));
        String sign = GetSign.genPackageSign(list);
        if (firstLoade==0){

            showProgrees("");
        }
        firstLoade++;
        RequestParams params = new RequestParams();
        params.addQueryStringParameter("rnd", i + "");
        params.addQueryStringParameter("sign", sign);
        HttpUtilsSingle.doGet(this, false, Constant.Getbrand_recommendation_list, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                String jsonString = responseInfo.result.toString();
                try {
                    JSONObject json = new JSONObject(jsonString);
                    String Errcode = json.getString("ErrCode");
                    String Errmsg = json.getString("ErrMsg");
                    String Response = json.getString("Response");
                    Gson gson = new Gson();
                    List<BrandModel> newlist = new ArrayList<BrandModel>();
                    switch (Integer.valueOf(Errcode)) {
                        case 1:// 失败
                            ToastUtils.showToast(Errmsg);
                            newlist = new ArrayList<BrandModel>();
                            hideProgree();
                            return;
                        case 0:// 成功
                            newlist = gson.fromJson(Response, new TypeToken<ArrayList<BrandModel>>() {
                            }.getType());
                            adapter.setList(newlist);
                            adapter.notifyDataSetChanged();
                            hideProgree();
                            return;
                        case 2:
                            ToastUtils.showToast(Errmsg);
                            newlist = new ArrayList<BrandModel>();
                            hideProgree();
                            return;
                    }
//                    if (mIsLoad) {// 上拉时（加载）
//                        List<BrandModel> li = adapter.getList();
//                        li.addAll(newlist);
//                        pullrefreshscrollview.onPullUpRefreshComplete();
//                        if (isNullDate(li)) {
//                            adapter.setList(li);
//                            adapter.notifyDataSetChanged();
//                        }
//                    } else {// 下拉时（刷新）
//                        pullrefreshscrollview
//                                .onPullDownRefreshComplete();
//                        if (isNullDate(newlist)) {
//                            adapter.setList(newlist);
//                            adapter.notifyDataSetChanged();
//                        }
//                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(HttpException error, String msg) {
                ToastUtils.showToast("获取数据失败,请检查网络！");
            }
        });
    }

    /**
     * @tab 判断listview是否有值
     */
    private boolean isNullDate(List rewordList) {
        if (rewordList == null || rewordList.size() == 0) {
            null_information_layout.setVisibility(View.VISIBLE);
            listView.setVisibility(View.GONE);
            return false;
        } else {
            null_information_layout.setVisibility(View.GONE);
            listView.setVisibility(View.VISIBLE);
            return true;
        }
    }

    @Override
    public void onPullDownToRefresh(PullToRefreshBase<ScrollView> refreshView) {//刷新
        pullrefreshscrollview.setLastUpdatedLabel(DateTimeUtil
                .getFormatDateTime(DateTimeUtil.getCurrTimestamp()));
        mIsLoad = false;
        page = 1;
    }

    @Override
    public void onPullUpToRefresh(PullToRefreshBase<ScrollView> refreshView) {//加载
        pullrefreshscrollview.setLastUpdatedLabel(DateTimeUtil
                .getFormatDateTime(DateTimeUtil.getCurrTimestamp()));
        mIsLoad = true;
        page++;
    }
}
